<template>
  <view class="admin-category-page">
    <view class="page-header">
      <view class="header-left">
        <view class="back-btn" @click="navigateBack">
          <view class="icon icon-arrow-left" style="font-size: 20px;">‹</view>
          <text class="header-title">分类管理</text>
        </view>
      </view>
      <view class="header-right">
        <button class="add-btn" type="primary" size="mini" @click="navigateToAdd">
          新增分类
        </button>
      </view>
    </view>
    
    <!-- 分类列表 -->
    <view class="category-list">
      <view 
        v-for="category in categories" 
        :key="category._id" 
        class="category-item"
      >
        <view class="category-info">
          <text class="category-name">{{ category.name }}</text>
          <text class="category-count">壁纸数量: {{ category.wallpaperCount || 0 }}</text>
        </view>
        <view class="action-buttons">
          <button size="mini" type="warn" @click="editCategory(category)">编辑</button>
          <button size="mini" type="default" @click="deleteCategory(category._id, category.name)">删除</button>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-if="categories.length === 0 && !isLoading" class="empty-state">
      <view class="icon icon-grid" style="font-size: 64px; color: #ccc;">📊</view>
      <text class="empty-text">暂无分类</text>
      <button class="create-btn" type="primary" @click="navigateToAdd">
        创建第一个分类
      </button>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-state">
      <uni-load-more :status="'loading'" />  
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onReady,onLoad } from '@dcloudio/uni-app';

// 状态管理
const categories = ref([]);
const isLoading = ref(false);

// 生命周期
onLoad(() => {
  // 移除管理员权限校验
  loadCategories();
});

// 管理员权限校验已移除

// 加载分类数据
const loadCategories = async () => {
  isLoading.value = true;
  
  try {
    const res = await uniCloud.callFunction({
      name: 'admingetCategories'
    });
    
    if (res && res.result && res.result.code === 0) {
      categories.value = res.result.data || [];
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    // 使用模拟数据
    mockCategories();
  } finally {
    isLoading.value = false;
  }
};

// 模拟分类数据
const mockCategories = () => {
  categories.value = [
    { _id: '1', name: '自然风光', wallpaperCount: 24 },
    { _id: '2', name: '城市建筑', wallpaperCount: 18 },
    { _id: '3', name: '抽象艺术', wallpaperCount: 32 },
    { _id: '4', name: '动物世界', wallpaperCount: 16 },
    { _id: '5', name: '人文历史', wallpaperCount: 12 }
  ];
};

// 编辑分类
const editCategory = (category) => {
  uni.navigateTo({
    url: `/pages/admin/edit-category?id=${category._id}&name=${encodeURIComponent(category.name)}`
  });
};

// 删除分类
const deleteCategory = (categoryId, categoryName) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除分类"${categoryName}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // 显示加载提示
          uni.showLoading({
            title: '删除中...'
          });
          
          // 确保调用正确的云函数
          const result = await uniCloud.callFunction({
            name: 'admindeleteCategory',
            data: { id: categoryId,uid:uniCloud.getCurrentUserInfo().uid }
          });
          
          uni.hideLoading();
          
          console.log('删除分类结果:', result);
          
          if (result && result.result) {
            if (result.result.code === 0) {
              uni.showToast({ 
                title: '删除成功', 
                icon: 'success',
                duration: 1500,
                complete: () => {
                  // 重新加载分类列表
                  setTimeout(() => {
                    loadCategories();
                  }, 1500);
                }
              });
            } else if (result.result.code === 404) {
              // 分类不存在的特殊处理
              uni.showToast({ 
                title: '该分类不存在或已被删除', 
                icon: 'none'
              });
              // 重新加载列表以同步最新状态
              setTimeout(() => {
                loadCategories();
              }, 1500);
            } else if (result.result.code === 400) {
              // 业务逻辑错误，如分类下有壁纸
              uni.showToast({ 
                title: result.result.message || '删除失败', 
                icon: 'none',
                duration: 2500
              });
            } else {
              uni.showToast({ 
                title: result.result.message || '删除失败', 
                icon: 'none'
              });
            }
          } else {
            uni.showToast({ 
              title: '云函数调用异常', 
              icon: 'none'
            });
          }
        } catch (error) {
          uni.hideLoading();
          console.error('删除分类异常:', error);
          
          // 显示更友好的错误信息
          let errorMessage = '删除失败，请稍后重试';
          if (error?.message) {
            errorMessage = `删除失败: ${error.message}`;
          }
          
          uni.showToast({ 
            title: errorMessage,
            icon: 'none',
            duration: 2500
          });
        }
      }
    }
  });
};

// 导航返回
const navigateBack = () => {
  uni.navigateBack();
};

// 跳转到新增分类页面
const navigateToAdd = () => {
  uni.navigateTo({
    url: '/pages/admin/add-category'
  });
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.admin-category-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-top: 50rpx;
    .header-left {
      .back-btn {
        display: flex;
        align-items: center;
        
        .header-title {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-left: 4px;
        }
      }
    }
    
    .header-right {
      .add-btn {
        font-size: 14px;
      }
    }
  }
  
  .category-list {
    padding: 16px;
    
    .category-item {
      background-color: #fff;
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .category-info {
        .category-name {
          display: block;
          font-size: 16px;
          font-weight: 500;
          color: #333;
          margin-bottom: 4px;
        }
        
        .category-count {
          display: block;
          font-size: 12px;
          color: #666;
        }
      }
      
      .action-buttons {
        display: flex;
        gap: 12px;
        
        button {
          font-size: 12px;
          height: 28px;
          line-height: 28px;
        }
      }
    }
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 64px 0;
    
    .empty-text {
      font-size: 14px;
      color: #999;
      margin: 16px 0 24px;
    }
    
    .create-btn {
      font-size: 14px;
    }
  }
  
  .loading-state {
    padding: 24px 0;
    display: flex;
    justify-content: center;
  }
}
</style>